<?php
declare(strict_types=1);

namespace lib\middleware;

use Swoole\Http\Request;
use Swoole\Http\Response;

class NetbarAuth
{
    public static function handle(Request $request, Response $response, mixed $obj)
    {
        if($origin = ($request->header['origin'] ?? null)){
            $response->header('Access-Control-Allow-Origin', $origin);
            $response->header('Access-Control-Allow-Headers', '*');
        }

        # 忽略 WebSocket
        if(!empty($request->header['upgrade'])){
            return;
        }

        $response->header('Content-Type', 'application/json');

        if($request->server['request_method']==='OPTIONS'){
            return '';
        }

        if(empty($request->header['x-token'])){
            return ['success'=>false, 'message'=>'非法请求.'];
        }

        $token = $request->header['x-token'];

        $login = \lib\LoginTokens::get($token);
        if(null === $login){
            $db = new \sys\Db();
            if(null === ($tokenr = $db->table('el_token')->where([['token','=', $token], ['plat_id','=', 0]])->find())){
                return ['success'=>false, 'message'=>'登录已经失效.'];
            }

            if(null === ($merchant = \lib\Merchant::get($tokenr['auth']['mid']))){
                \lib\Merchant::initMerchants([$tokenr['auth']['mid']]);
                $merchant = \lib\Merchant::get($tokenr['auth']['mid']);
            }

            if(null === ($user = \lib\User::get($tokenr['auth']['id']))){
                return ['success'=>false, 'message'=>'用户不存在.'];
            }
            $login = new \lib\LoginTokens($token, $user);
        }else{
            $merchant = \lib\Merchant::get($login->user->mid);
        }

        $obj->user      = $login->user;
        $obj->merchant  = $merchant;
        $obj->token     = $token;
    }
}